<template>
  <div class="face-unlock-container">
    <div class="face-unlock-content">
      <h1 class="face-unlock-title">人脸识别</h1>
      <p class="face-unlock-subtitle">请将面部对准摄像头，系统将自动进行人脸识别</p>
      
      <div class="face-unlock-main">
        <!-- 摄像头和人脸采集 -->
        <div class="face-camera-section">
          <div class="face-camera-title">人脸采集</div>
          <div class="face-camera-preview-wrapper">
            <div class="face-camera-frame">
              <video ref="videoRef" autoplay playsinline width="480" height="360" />
              <div v-if="!cameraOpened" class="face-camera-placeholder">
                <i class="el-icon-loading"></i>
                <span>正在开启摄像头...</span>
              </div>
              <div v-if="scanning" class="face-scanning-overlay">
                <div class="scanning-line"></div>
              </div>
            </div>
          </div>
          <div class="face-scan-status">
            <div class="scan-status-indicator active">
              <i class="el-icon-refresh"></i>
              <span>{{ statusMessage }}</span>
            </div>
          </div>
        </div>
        
                  <!-- 状态显示 -->
                <div class="face-status-section">
                  <div class="status-card">
                    <h3 class="status-title">识别状态</h3>
                    <div class="status-display" :class="statusClass">
                      {{ statusMessage }}
                    </div>
                    
                    <!-- 锁选择 -->
                    <div class="lock-selection">
                      <h3 class="lock-title">选择锁</h3>
                      <div class="lock-options">
                        <el-radio-group v-model="selectedLockId">
                          <el-radio :label="1">锁 1</el-radio>
                          <el-radio :label="2">锁 2</el-radio>
                          <el-radio :label="3">锁 3</el-radio>
                          <el-radio :label="4">锁 4</el-radio>
                        </el-radio-group>
                      </div>
                    </div>
                  </div>
                </div>
      </div>
      
      <div class="unlock-history" v-if="unlockHistory.length > 0">
        <h3 class="history-title">识别记录</h3>
        <el-table :data="unlockHistory" style="width: 100%">
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.success ? 'success' : 'danger'">
                {{ scope.row.success ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  captureImageFromVideo, 
  faceRecognition
} from '../api/opencv';

// 状态变量
const videoRef = ref(null);
const cameraOpened = ref(false);
const scanning = ref(false);
const statusMessage = ref('正在初始化...');
const statusClass = ref('status-waiting');
const unlockHistory = ref([]);
const selectedLockId = ref(1); // 默认选择锁1

// 打开摄像头
async function openCamera() {
  if (cameraOpened.value) return;
  
  if (!videoRef.value) {
    console.error('视频元素未初始化，请刷新页面重试');
    statusMessage.value = '摄像头初始化失败，请刷新页面';
    statusClass.value = 'status-error';
    return;
  }
  
  try {
    statusMessage.value = '正在开启摄像头...';
    
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'user' // 使用前置摄像头
      }
    });
    
    videoRef.value.srcObject = stream;
    
    videoRef.value.onloadedmetadata = () => {
      videoRef.value.play()
        .then(() => {
          cameraOpened.value = true;
          statusMessage.value = '摄像头已开启，正在扫描...';
          // 开始自动扫描
          startAutoScan();
        })
        .catch(err => {
          console.error('视频播放失败:', err);
          statusMessage.value = '视频播放失败，请刷新页面';
          statusClass.value = 'status-error';
        });
    };
  } catch (err) {
    console.error('摄像头访问失败:', err);
    statusMessage.value = '无法访问摄像头，请确保已授予权限';
    statusClass.value = 'status-error';
  }
}

// 关闭摄像头
function closeCamera() {
  if (videoRef.value && videoRef.value.srcObject) {
    const tracks = videoRef.value.srcObject.getTracks();
    tracks.forEach(track => track.stop());
    videoRef.value.srcObject = null;
  }
  
  cameraOpened.value = false;
}

// 自动扫描相关变量
const autoScanInterval = ref(null);
const autoScanDelay = 3000; // 自动扫描间隔，单位毫秒
const scanAttempts = ref(0);
const maxScanAttempts = 20; // 最大扫描尝试次数，防止无限循环

// 自动扫描函数
async function startAutoScan() {
  if (!cameraOpened.value || !videoRef.value) {
    statusMessage.value = '等待摄像头准备就绪...';
    // 如果摄像头未准备好，1秒后重试
    setTimeout(startAutoScan, 1000);
    return;
  }
  
  try {
    // 增加扫描尝试次数
    scanAttempts.value++;
    
    // 如果超过最大尝试次数，暂停一段时间后重置计数
    if (scanAttempts.value > maxScanAttempts) {
      statusMessage.value = '暂停扫描，稍后将继续...';
      statusClass.value = 'status-waiting';
      
      // 5秒后重置计数并继续扫描
      setTimeout(() => {
        scanAttempts.value = 0;
        startAutoScan();
      }, 5000);
      
      return;
    }
    
    // 捕获图像
    scanning.value = true;
    statusMessage.value = '正在扫描人脸...';
    statusClass.value = 'status-scanning';
    
    const base64Image = captureImageFromVideo(videoRef.value);
    
    // 发送人脸识别请求
    statusMessage.value = '正在验证身份...';
    console.log('调用人脸识别接口...锁ID:', selectedLockId.value);
    const response = await faceRecognition(base64Image, selectedLockId.value);
    console.log('人脸识别响应:', response);
    
    // 处理响应
    handleUnlockResponse(response);
    
    // 如果成功识别，暂停一段时间再继续扫描
    if (response.data && response.data.code === 200) {
      // 成功后等待10秒再继续扫描
      setTimeout(startAutoScan, 10000);
    } else {
      // 失败后继续扫描
      autoScanInterval.value = setTimeout(startAutoScan, autoScanDelay);
    }
  } catch (error) {
    console.error('自动扫描出错:', error);
    statusMessage.value = '扫描失败: ' + (error.message || '未知错误');
    statusClass.value = 'status-error';
    
    // 出错后短暂延迟再继续扫描
    autoScanInterval.value = setTimeout(startAutoScan, autoScanDelay);
  } finally {
    scanning.value = false;
  }
}

// 处理人脸识别响应
function handleUnlockResponse(response) {
  console.log('人脸识别响应:', response);
  
  if (response.data && response.data.code === 200) {
    statusMessage.value = '识别成功!';
    statusClass.value = 'status-success';
    ElMessage.success('人脸识别成功');
    
    // 如果响应中包含token，记录到控制台
    if (response.data.data) {
      console.log('获取到token:', response.data.data);
    }
    
    // 重置扫描尝试次数
    scanAttempts.value = 0;
    
    // 添加到历史记录
    addToHistory(true, '识别成功');
  } else {
    const errorMsg = response.data?.message || '未知错误';
    statusMessage.value = '识别中...';
    statusClass.value = 'status-scanning';
    
    // 添加到历史记录（仅在特定错误时）
    if (scanAttempts.value % 5 === 0) { // 每5次失败记录一次，避免记录过多
      addToHistory(false, errorMsg);
    }
  }
}

// 添加到历史记录
function addToHistory(success, message) {
  unlockHistory.value.unshift({
    time: new Date().toLocaleString(),
    success: success,
    message: message
  });
  
  // 限制历史记录数量
  if (unlockHistory.value.length > 10) {
    unlockHistory.value.pop();
  }
}

// 生命周期钩子
onMounted(() => {
  // 自动开启摄像头
  setTimeout(() => {
    openCamera();
  }, 500);
});

onBeforeUnmount(() => {
  // 清除自动扫描定时器
  if (autoScanInterval.value) {
    clearTimeout(autoScanInterval.value);
    autoScanInterval.value = null;
  }
  
  // 关闭摄像头
  closeCamera();
});
</script>

<style src="../assets/css/lock-selection.css"></style>
<style scoped>
.face-unlock-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e3eafc 0%, #f7faff 100%);
  padding: 40px 20px;
}

.face-unlock-content {
  width: 1000px;
  max-width: 95%;
  margin: 0 auto;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 10px 40px rgba(60,120,240,0.15), 0 2px 10px rgba(0,0,0,0.05);
  padding: 40px;
  animation: fadeIn 0.6s ease-out;
}

.face-unlock-title {
  font-size: 2.2rem;
  font-weight: 700;
  color: #3a5ad7;
  margin-bottom: 8px;
  text-align: center;
  letter-spacing: 2px;
}

.face-unlock-subtitle {
  font-size: 1.1rem;
  color: #7a8599;
  text-align: center;
  margin-bottom: 40px;
}

.face-unlock-main {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
  margin-bottom: 40px;
}

/* 摄像头部分 */
.face-camera-section {
  flex: 1;
  min-width: 500px;
  padding: 30px;
  background: #f9fbff;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(60,120,240,0.08);
  border: 1px solid #e6eeff;
}

.face-camera-title {
  font-size: 1.4rem;
  font-weight: 600;
  color: #3a5ad7;
  margin-bottom: 20px;
  text-align: center;
}

.face-camera-preview-wrapper {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.face-scan-status {
  display: flex;
  justify-content: center;
  margin-bottom: 5px;
}

.scan-status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  background: #f0f5ff;
  color: #7a8599;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.scan-status-indicator.active {
  background: #e6f7ff;
  color: #1890ff;
}

.scan-status-indicator.active i {
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.face-camera-frame {
  position: relative;
  width: 100%;
  max-width: 480px;
  height: 360px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(58,90,215,0.13), 0 1.5px 8px rgba(0,0,0,0.06);
  border: 3px solid #3a5ad7;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.face-camera-frame video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 16px;
}
</style>